Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },

  bindGetUserInfo(e) {
    if (e.detail.userInfo) {
      this.getLoginInfo().then(res => {
        wx.request({
          url: 'https://api.mokyun.com/pesticide/login',
          method: 'POST',
          header: {
            'Accept': 'application/json',
            'Authorization': 'Bearer ' + wx.getStorageSync('token'),
            'content-type': 'application/json',
            'APPID': 32
          },
          success(res) {
            if (!res.data.tel) {
              wx.redirectTo({
                url: '/pages/certification/certification'
              });
            } else {
              wx.redirectTo({
                url: '/pages/index/index'
              });
            }
            wx.hideLoading();
          }
        })
      }).catch(res => {
        
      });
    } else {
      wx.showModal({
        title: '警告',
        content: '你点击了拒绝按钮',
        showCancel: true,
        cancelText: "取消",
        cancelColor: '#000000',
        confirmText: "返回授权",
        confirmColor: "#000000",
        success: function(res) {}
      })
    }
  },
  getLoginInfo() {
    // 登录
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '登录中',
      })
      wx.getSetting({
        success: res => {
          // 获取授权
          wx.getUserInfo({
            success: res => {
              getApp().globalData.userInfo = {
                userName: res.userInfo.nickName,
                headImgUrl: res.userInfo.avatarUrl
              }
              wx.login({
                success: res => {
                  // 获取用户信息
                  wx.request({
                    url: 'https://api.mokyun.com/wxusers/authenticate/miniProgram',
                    method: 'POST',
                    data: {
                      code: res.code
                    },
                    header: {
                      APPID: 32
                    },
                    success(res) {
                      if (res.data.token) {
                        wx.setStorageSync('token', res.data.token);
                        resolve()
                      }
                    }
                  })
                }
              })
            }
          })
        }
      })
    })
  }
})